package com.myblog.demo.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkdownUtils {

    /**
     * 移除Markdown格式，保留纯文本内容。
     *
     * @param input 带有Markdown格式的输入文本
     * @return 移除Markdown格式后的纯文本
     */
    public static String removeMarkdown(String input) {
        String withoutMarkdown = input;

        // 移除标题
        withoutMarkdown = removePattern(withoutMarkdown, "^#+\\s+");

        // 移除列表项
        withoutMarkdown = removePattern(withoutMarkdown, "^[\\*\\-]+\\s+");

        // 移除引用块
        withoutMarkdown = removePattern(withoutMarkdown, "^>\\s+");

        // 移除行内代码
        withoutMarkdown = removePattern(withoutMarkdown, "`([^`]+)`");

        // 移除图片
        withoutMarkdown = removePattern(withoutMarkdown, "!\\[[^\\]]*\\]\\([^)]+\\)");

        // 移除加粗格式
        withoutMarkdown = removePattern(withoutMarkdown, "\\*\\*([^*]+)\\*\\*");

        return withoutMarkdown;
    }

    private static String removePattern(String input, String pattern) {
        Pattern p = Pattern.compile(pattern, Pattern.MULTILINE);
        Matcher m = p.matcher(input);
        return m.replaceAll("");
    }
}

